import org.jsecurity.authc.AuthenticationException
import org.jsecurity.authc.UsernamePasswordToken
import org.jsecurity.SecurityUtils

class LoginController {
	
	CryptoService cryptoService
	
	def jsecSecurityManager
	
	def index = { redirect(action: 'login', params: params)
	}
	
	def login = {
		return [ username: params.username, rememberMe: (params.rememberMe != null), targetUri: params.targetUri ]
	}
	
	def signin = {
		
		if (!params.password) {
			redirect(action: 'login', params: params)
			return
		}
		
		String passwordHash = cryptoService.encrypt(params.password.getBytes())
		def authToken = new UsernamePasswordToken(params.username, params.password)
		
		// Support for "remember me"
		if (params.rememberMe) {
			authToken.rememberMe = true
		}
		
		try{
			// Perform the actual login. An AuthenticationException
			// will be thrown if the username is unrecognised or the
			// password is incorrect.
			this.jsecSecurityManager.login(authToken)
			
			// If a controller redirected to this page, redirect back
			// to it. Otherwise redirect to account.
			def targetUri = params.targetUri ?: "/"
			
			//Put the account in session
			session.account = Account.findByUsername(params.username);
			if (targetUri != "/") {
				redirect(uri: targetUri)
				return
			} else {
				redirect(controller:'account')
				return
			}
		}
		catch (AuthenticationException ex){
			// Authentication failed, so display the appropriate message
			// on the login page.
			
			// Keep the username and "remember me" setting so that the
			// user doesn't have to enter them again.
			def m = [ username: params.username ]
			if (params.rememberMe) {
				m['rememberMe'] = true
			}
			
			// Remember the target URI too.
			if (params.targetUri) {
				m['targetUri'] = params.targetUri
			}
			
			flash.message = "Invalid username and/or password"
			
			// Now redirect back to the login page.
			render(view: 'login', params: m)
		}
	}
	
	def logout = {
		// Log the user out of the application.
		SecurityUtils.subject?.logout()
		
		flash.message = "You have successfully logged out"
		render(view: 'login')
	}
	
	def unauthorized = {
		render 'You do not have permission to access this page.'
	}
}
